package string.nowcoder.easy;

import java.util.Scanner;

/**
 * @author Stark
 * @description 字符串转整数
 * @date 2022/4/23 16:54
 **/
public class StringToInt {
    static int choice = 2;
    public static int stringToInt(String str){
        if(choice == 1) {
            int length = str.length();
            if (str.equals("0") || length == 0 || length >= 14) {
                return 0;
            }
            for (int i = 1; i < length; i++) {
                char ch = str.charAt(i);
                if (ch < '0' || ch > '9')
                    return 0;
            }
            int num = 0;
            char ch = str.charAt(0);
            if (ch >= '0' && ch <= '9') {
                for (int i = 0; i < length; i++) {
                    num = num * 10 + (str.charAt(i) - '0');
                }
            } else {
                for (int i = 1; i < length; i++) {
                    num = num * 10 + (str.charAt(i) - '0');
                }
            }
            if (ch == '-')
                num = -num;
            return num;
        }

        //优化写法
        //将字符串转为char[]数组进行处理
        //对数组第一位进行特殊处理
        if(choice == 2){
            char[] arr = str.toCharArray();
            if(arr.length == 0)
                return 0;
            int flag = 1;
            if(arr[0] == '-'){
                flag = -1;
                arr[0] = '0';
            }else if(arr[0] == '+'){
                arr[0] = '0';
            }
            int sum = 0;
            for (int i = 0; i < arr.length; i++) {
                if(arr[i] < '0' || arr[i] > '9'){
                    sum = 0;
                    break;
                }
                sum = sum * 10 + arr[i] - '0';
            }
            return sum * flag;
        }
        return 0;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNextLine()){
            String str = scanner.nextLine();
            System.out.println(stringToInt(str));
        }
    }
}
